import { blogLoginAPI, whoAmIAPI, blogLoginOutAPI } from "@/api/login.js";
import { setToken, removeToken, getToken, setSiteTitle } from "@/utils";

export default {
  namespaced: true,
  state: {
    isLoading: false,
    user: null,
  },
  getters: {
    stateNow: (state) => {
      if (state.isLoading) {
        return "loading";
      } else if (state.user) {
        setSiteTitle(state.user.blogName);
        return "logined";
      } else {
        return "logouted";
      }
    },
  },
  mutations: {
    setLoading(state, payload) {
      state.isLoading = payload;
    },
    setUser(state, payload) {
      state.user = payload;
    },
  },
  actions: {
    async login(ctx, payload) {
      ctx.commit("setLoading", true);
      const res = await blogLoginAPI(payload);
      ctx.commit("setLoading", false);
      if (res && res?.code === 0) {
        ctx.commit("setUser", res.data.user);
        setToken(res.data.token);
      } else {
        ctx.commit("setUser", null);
        removeToken();
      }
      return res;
    },
    async whoAmI(ctx) {
      const token = getToken();
      if (!token) {
        return;
      }
      ctx.commit("setLoading", true);
      const res = await whoAmIAPI(token);
      ctx.commit("setLoading", false);
      if (res.code === 0) {
        ctx.commit("setUser", res.data.user);
        setToken(res.data.token);
      } else {
        ctx.commit("setUser", null);
        removeToken();
      }
      return res;
    },

    async loginOut(ctx) {
      ctx.commit("setLoading", true);
      await blogLoginOutAPI();
      ctx.commit("setUser", null);
      removeToken();
      ctx.commit("setLoading", false);
    },
  },
};
